package com.purengage.ipilih;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.markupartist.android.widget.PullToRefreshListView;
import com.markupartist.android.widget.PullToRefreshListView.OnRefreshListener;
import com.purengage.ipilih.lib.DBClass;
import com.purengage.ipilih.lib.EntryAdapter;
import com.purengage.ipilih.lib.EntryItem;
import com.purengage.ipilih.lib.FormatDate;
import com.purengage.ipilih.lib.HttpConnect;
import com.purengage.ipilih.lib.Item;
import com.purengage.ipilih.lib.SectionItem;
import com.purengage.ipilih.lib.Surveys;

import android.annotation.SuppressLint;
import android.app.ListActivity;
import android.content.Intent;

import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

@SuppressLint("SimpleDateFormat")
public class Survey extends ListActivity implements OnItemClickListener {
	Button btn1;
	ArrayList<Item> items = new ArrayList<Item>();
	ListView listview = null;
	List<Surveys> dataList;
	List<Surveys> dataList2;

	public class survey extends AsyncTask<String, String, Boolean> {
		DBClass db = new DBClass(Survey.this);

		@Override
		protected Boolean doInBackground(String... params) {

			String dateModif = (db.getDateSurvey().equalsIgnoreCase("")) ? "2013-09-1"
					: db.getDateSurvey();

			String uri = "http://purengage.com/api/surveys?client_id="
					+ getResources().getString(R.string.client_id) + "&token="
					+ db.getValue("token") + "&indent=" + params[0]
					+ "&since_date_modified="
					+ dateModif.replaceAll("\\s+", "%20");

			HttpConnect http = new HttpConnect(uri);
			String output = "";
			Log.d("uri", uri);
			boolean res = http.getData();
			if (res) {
				output = http.getOutput();

				JSONObject jobj, ijobj;
				try {
					jobj = new JSONObject(output);
					ijobj = jobj.getJSONObject("data");
					JSONArray json = ijobj.getJSONArray("surveys");
					Surveys s = new Surveys();
					for (int i = 0; i < json.length(); i++) {
						JSONObject job = json.getJSONObject(i);
						s.setId(job.getInt("id"));
						s.setTitle(job.getString("title"));
						s.setTarget_total(job.getInt("target_total"));
						s.setTarget_qualification(job
								.getString("target_qualification"));
						s.setPoints_per_data(job.getInt("points_per_data"));
						s.setDate_stop(job.getString("date_stop"));
						s.setDate_modified(job.getString("date_modified"));
						s.setStatus(job.getString("status"));
						s.setIs_locked(job.getString("is_locked"));
						s.setDescription(job.getString("description"));
						s.setOptions(job.getString("options"));

						db.insertSurvey(s);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}

			}

			return res;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);
			((PullToRefreshListView) getListView()).onRefreshComplete();

			if (!result)
				Toast.makeText(
						Survey.this,
						"Tidak dapat menghubungi server, periksa setting internet anda",
						Toast.LENGTH_LONG).show();
			else {
				items.clear();
				ListAll();
			}

		}

	}

	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_survey);

		((PullToRefreshListView) getListView())
				.setOnRefreshListener(new OnRefreshListener() {
					public void onRefresh() {
						new survey().execute("1");
					}
				});

		ListAll();
	}

	public void ListAll() {

		DBClass db = new DBClass(this);
		dataList = db.getListSurveys();
		dataList2 = db.getListSurveys();
		SimpleDateFormat curFormater = new SimpleDateFormat("yyyy-MM-dd");
		Date tanggal, now;
		ListView lv = getListView();

		if (dataList.size() > 0)
			items.add(new SectionItem("Survey Terkini"));

		for (Surveys s : dataList) {
			try {
				now = curFormater.parse(curFormater.format(new Date()));
				tanggal = curFormater.parse(s.getDate_stop());				
				if (tanggal.after(now)) {
					items.add(new EntryItem(R.drawable.survey_b, s.getTitle(),
							new FormatDate().convert(s.getDate_stop()), "70%",
							s.getId() + ""));
				}
			} catch (ParseException e) {				
				e.printStackTrace();
			}
		}

		if (dataList2.size() > 0)
			items.add(new SectionItem("Survey Lalu"));

		for (Surveys s : dataList2) {
			try {
				now = curFormater.parse(curFormater.format(new Date()));
				tanggal = curFormater.parse(s.getDate_stop());				
				if (tanggal.before(now)) {
					items.add(new EntryItem(R.drawable.survey_g, s.getTitle(),
							new FormatDate().convert(s.getDate_stop()), "70%",
							s.getId() + ""));					
				}
			} catch (ParseException e) {
				e.printStackTrace();
			}

		}

		EntryAdapter adapter = new EntryAdapter(this, items);
		lv.setAdapter(adapter);
		lv.setOnItemClickListener(this);
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int position,
			long arg3) {

		EntryItem item = (EntryItem) items.get(position - 1);
		Intent i = new Intent(Survey.this, Survey2.class);

		i.putExtra("id", item.id);

		DBClass db = new DBClass(Survey.this);
		Surveys s = db.getSurveyById(Integer.parseInt(item.id));

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date stop = null;
		try {
			stop = sdf.parse(s.getDate_stop());
		} catch (ParseException e) {
			e.printStackTrace();
		}

		//if (!stop.before(new Date()) && s.getIs_locked().equalsIgnoreCase("0"))
		//if (!stop.before(new Date()))
			startActivity(i);

	}

}
